package com.dolphin.config;

import com.dolphin.model.Permission;
import com.dolphin.permission.MenuManager;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * Shiro Configuration
 *
 * @author dolphin
 */
@Configuration
public class ShiroConfig {

    private final static Logger LOGGER = LoggerFactory.getLogger(ShiroConfig.class);


    @Bean
    public ShiroRealm userRealm() {
        return new ShiroRealm();
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/login", "anon");
        chainDefinition.addPathDefinition("/doLogin", "anon");
        chainDefinition.addPathDefinition("/register", "anon");
        chainDefinition.addPathDefinition("/doRegister", "anon");
        chainDefinition.addPathDefinition("/restPassword", "anon");
        chainDefinition.addPathDefinition("/logout", "anon");
        chainDefinition.addPathDefinition("/404", "anon");
        chainDefinition.addPathDefinition("/500", "anon");
        chainDefinition.addPathDefinition("/403", "anon");
        chainDefinition.addPathDefinition("/api/401", "anon");
        chainDefinition.addPathDefinition("/install", "anon");
//        List<Permission> permissionList = MenuManager.initSystemPermission();
//        // 权限控制map.
//        Map filterChainDefinitionMap = new LinkedHashMap();
//        //从数据库获取
//        for (Permission permission : permissionList) {
//            filterChainDefinitionMap.put(permission.getUrl(),
//                    permission.getPermissionValue());
//        }
//        chainDefinition.addPathDefinitions(filterChainDefinitionMap);
        LOGGER.info("Shiro拦截器工厂类注入成功");
        return chainDefinition;
    }

    @Bean
    public SessionsSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm());
        return securityManager;
    }

    @Bean
    public static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setUsePrefix(true);
        return defaultAdvisorAutoProxyCreator;
    }
}
